const { parse } = require("@babel/parser");
const traverse = require("@babel/traverse");
const types = require("@babel/types");
const generator = require("@babel/generator");
const path = require("path");
const fs = require("fs");
const process = require("process");

function getManiFestCode() {
  const m_path = path.resolve(process.cwd(), "./src/manifest.json");
  const m_code = fs.readFileSync(m_path, "utf-8");

  return `var __manifestJsonCodeStr__ = ${m_code}`;
}
function writeManiFestCode(code) {
  const m_path = path.resolve(process.cwd(), "./src/manifest.json");
  fs.writeFileSync(m_path, code.replace("var __manifestJsonCodeStr__ = ", ""));
}

export function changeMpWeixinAppid(appid) {
  let sourceCode = getManiFestCode();
  let ast = parse(sourceCode);
  const visitor = {
    enter(path) {
      if (types.isObjectProperty(path.node)) {
        if (path.node.key.value === "appid") {
          path.node.value.value = appid;
        }
      }
    },
  };
  traverse.default(ast, visitor);
  let newCode = generator.default(ast, {}, sourceCode).code;
  writeManiFestCode(newCode);
}
